// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

var Serialport = require('serialport')
const tableify = require('tableify')
var http=require('http'); 

var serial_port_number="";
// var selectdeviceid='';
var epc="";
var serialPort="";
var oError = document.getElementById("error");
var onresult=document.getElementById('result_input');
var isconnect=false;
var ipc=require('electron');


Serialport.list().then( ports => {
  // console.log('ports', ports);
  // if (err) {
  //   document.getElementById('error').textContent = err.message
  //   return
  // } else {
  //   document.getElementById('error').textContent = ''
  // }

  // if (ports.length === 0) {
  //   document.getElementById('error').textContent = 'No ports discovered'
  // }

  // tableHTML = tableify(ports)
  // document.getElementById('ports').innerHTML = tableHTML


  ports.forEach(function(port){
    
    console.log(port.comName);
      // console.log(port.pnpId);
      // console.log(port.manufacturer);  


     var op=document.createElement("option");
     op.value=port.comName;

     var opdata=document.createTextNode(port.comName);
     op.appendChild(opdata);

     var ele=document.getElementById("select");

     ele.appendChild(op);


})

})




getlogindata();




function getlogindata(){

  const param = JSON.parse(localStorage.params);


  var gid=param.gid;

  var aid=param.aid;
 var url="";

  if(gid<7){


    url="http://www2.boohersmart.com:3000/api/device/listByGid/"+aid;

getDeviceId(url);


  }else{
url="http://www2.boohersmart.com:3000/api/device/select/info/"+aid

getDeviceId(url);
  }

}


 function getDeviceId(url) {

 

  console.log("re:"+url);


            
//get 请求外网  
http.get(url,function(req,res){  
    var html='';  
	console.log("已经发送请求");
	 //通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
    req.on('data',function(data){
	html+=data;  		
    });  
	//end事件
    req.on('end',function(){
   console.log(html);	
   var r=JSON.parse(html);

  //  for(var i=0;i<r.data.length;i++){
     
  //        devicedata=r.data[i].device_id;

  //  }

         var arr=r.data;

        arr.forEach(function(data){

  
          var op=document.createElement("option");
          op.value=data.device_id;


          var ele=document.getElementById("deviceid-select");
       
     var   opdata=document.createTextNode(data.device_id);
        op.appendChild(opdata);
      
         ele.appendChild(op);

        })

    


 

   console.log("ss:"+r.data.length);


  //  var op=document.createElement("option");
  //  op.value=



        })

      });


  }



function  sadd  (){

  var x=document.getElementById("serial_num")
  console.log("sadd:"+x.value)


 x.value++;

}

   
    function  serial_num_add(){

      

      var device_id=document.getElementById("deviceid-select").value;
      

        var serial_num=document.getElementById("serial_num");
        console.log("serial_num_add:"+serial_num)

        serial_num.value++;
          
       
       if(isconnect){
        


       httpget(device_id,serial_num.value);

       }
         



       
     

    

    }


    function  serial_num_subtract(){
      var device_id=document.getElementById("deviceid-select").value;
      var serial_num=document.getElementById("serial_num");
      if(serial_num.value>0){
       serial_num.value--;
      }else{
       
      }


      if(isconnect){
        httpget(device_id,serial_num.value);

      }
       
  
    }


function selectdata(data){

  serial_port_number=data;

}


// function selectdeviceid(data){

// selectdeviceid=data;
// }


  function connect(){




        var device_id=document.getElementById("deviceid-select").value;


        console.log("devi:"+device_id);

        var serial_num=document.getElementById("serial_num").value;
        // var select_spn=document.getElementById("select").options[0].value;
        

        // if(select_spn==0){
        //   console.log("slect_spn"+select_spn);
        //   oError.innerHTML="请选择串口号"

        //   return;
        // }

        if(serial_num==null){
          
          oError.innerHTML="serial_num不可为空"
        }


        ConnectSerialPort();

        httpget(device_id,serial_num);


   



  }




  function httpget(deviceid,serialnum){

//get 请求外网  
http.get('http://www2.boohersmart.com:3000/api/tool/select/basic/'+deviceid,function(req){  
    var html='';  
	console.log("已经发送请求");
	 //通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
    req.on('data',function(data){
	html+=data;  		
    });  
	//end事件
    req.on('end',function(){
   console.log(html);	


    
  var r=JSON.parse(html);

  
 document.getElementById("get_deviceid").value=r.data[serialnum].device_id;
 var drawer_id=   document.getElementById("get_drawerid").value=r.data[serialnum].drawer_id;
  document.getElementById("get_location").value=r.data[serialnum].location;
  var serial_num=  document.getElementById("get_serial_num").value=r.data[serialnum].serial_num;
  document.getElementById("get_part_no").value=r.data[serialnum].part_no;
  document.getElementById("get_part_des").value=r.data[serialnum].part_des;
  document.getElementById("inventory_num").value=r.data[serialnum].inventory_num;

  var str=drawer_id+serial_num;

  console.log("str",str);

  var shuju=str.substring(1);

  console.log("shuju",shuju);
   epc=strtohex(shuju);

  document.getElementById("epc").value= epc;
  


    });  
});




  }



  function strtohex(str){
    var val = "";
    for(var i = 0; i < str.length; i++){
     
          val += str.charCodeAt(i).toString(16);
      }
  
    return val;
  }


  function ConnectSerialPort(){

     var serial_port_number=document.getElementById('select');

    if(serial_port_number.value==0){

      oError.innerHTML="请选择串口号"
    }else{
       
      console.log("po:"+serial_port_number)
           

     serialPort =new Serialport(serial_port_number.value, {
      //波特率，可在设备管理器中对应端口的属性中查看
      baudRate : 115200,
      autoOpen:false
    })


    serialPort.open(function (err) {
        console.log('IsOpen:',serialPort.isOpen)
        console.log('err:',err)
    
    
        if(err){
            console.log("打开端口错误："+err);

            oError.innerHTML = "打开端口错误："+err;
        }else{

          isconnect=true;
            console.log("打开端口成功，正在监听数据中");
            oError.innerHTML = "打开端口成功";
    
        serialPort.on('data',function(data){
    
        
    
        })
    
      }
    
    
    
    
    
    })


    //指令监听
    serialPort.on('data',function (data) {
     console.log('data received: '+data.toString('hex'))
       console.log("length:"+data.length);

  if(data.length>12&&data.length<38){

      console.log("num:");

        readtag();

  }else if(data.length<12){
      var errorcode=data.toString('hex').substring(8,10);

      if(errorcode=36){
        onresult.value="无可操作标签"
      }

  }else if(data.length>38){

    var readepc=data.toString('hex').substring(18,42); 
    onresult.value=readepc;

  }

    })
    //错误监听
    serialPort.on('error',function (error) {
        console.log('error: '+error)
        oError.innerHTML = error;

    })

  }
    
    }


    function readtag(){
       
      


      const buf1 = new Buffer("A00A018101020600000000CB","hex");
       
 
    

      // console.log(item)
      serialPort.write(buf1, function (error, result) {
        
      })
    


    }


    
    function eachWrite(item) {


    
        //16进制Buffer流   
        
        var uncheckedwritetag="A016018200000000010206"+epc;

      var  sumcheckstr=  sumCheck(Str2Bytes(uncheckedwritetag),23);

      var sumcheckhex=Bytes2Str(number2Bytes(sumcheckstr));
      
       
        var writetag=uncheckedwritetag+sumcheckhex;

        console.log("writetag:"+writetag);

        const buf1 = new Buffer(writetag,"hex");
       
 
    

      // console.log(item)
      serialPort.write(buf1, function (error, result) {
        
      })
    
  }

  function hexToString(str){
    　　　　var val="";
    　　　　var arr = str.split(",");
    　　　　for(var i = 0; i < arr.length; i++){
    　　　　　　val += arr[i].fromCharCode(i);
    　　　　}
    　　　　return val;
    　　}

function sumCheck( b, len){
    var sum = 0;
    for(var i = 0; i < len; i++){
        sum = sum + b[i];
    }
    if(sum > 0xff){ //超过了255，使用补码（补码 = 原码取反 + 1）
        sum = ~sum;
        sum = sum + 1;
    }
    return (sum & 0xff);
}

function number2Bytes(i) {
  var arr = new Int8Array(1);
  arr[0] = 0;
  var buf = Buffer.from(arr.buffer, 'hex');
  buf.writeUInt8(i);
   
  console.log("buf:", buf);
  console.log("buffer length :", buf.length); 
  var iNumber = buf.readInt8();
  console.log("iNumber:", iNumber);
  return buf;
  };

function Str2Bytes(str)

{

    var pos = 0;

    var len = str.length;

    if(len %2 != 0)

    {

       return null; 

    }

    len /= 2;

    var hexA = new Array();

    for(var i=0; i<len; i++)

    {

       var s = str.substr(pos, 2);

       var v = parseInt(s, 16);

       hexA.push(v);

       pos += 2;

    }

    return hexA;

}
function stringToHex(str){
  　　　　var val="";
  　　　　for(var i = 0; i < str.length; i++){
  　　　　　　if(val == "")
  　　　　　　　　val = str.charCodeAt(i).toString(16);
  　　　　　　else
  　　　　　　　　val += "," + str.charCodeAt(i).toString(16);
  　　　　}
  　　　　return val;
  　　}

function Bytes2Str(arr)

{

    var str = "";

    for(var i=0; i<arr.length; i++)

    {

       var tmp = arr[i].toString(16);
       console.log("tmp"+tmp)

       if(tmp.length == 1)

       {

           tmp = "0" + tmp;

       }

       str += tmp;

    }

    return str;

}

function hexCharCodeToStr(hexCharCodeStr) {
  　　var trimedStr = hexCharCodeStr.trim();
  　　var rawStr = 
  　　trimedStr.substr(0,2).toLowerCase() === "0x"
  　　? 
  　　trimedStr.substr(2) 
  　　: 
  　　trimedStr;
  　　var len = rawStr.length;
  　　if(len % 2 !== 0) {
  　　　　alert("Illegal Format ASCII Code!");
  　　　　return "";
  　　}
  　　var curCharCode;
  　　var resultStr = [];
  　　for(var i = 0; i < len;i = i + 2) {
  　　　　curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
  　　　　resultStr.push(String.fromCharCode(curCharCode));
  　　}
  　　return resultStr.join("");
  }

